#include <iostream>
#include <memory>
#include <sstream>
#include <algorithm>
#include <windows.h>
#include "TaskManager.h"
#include "DataStore.h"
#include "Command.h"
#include "Logger.h"

void initSystemEncoding() {
    SetConsoleOutputCP(CP_UTF8);
    SetConsoleCP(CP_UTF8);
    
    try {
        std::locale::global(std::locale("en_US.UTF-8"));
    } catch (const std::exception& e) {
        std::cerr << "Warning: Failed to set locale to UTF-8: " << e.what() << std::endl;
    }
}

/**
 * @brief 显示帮助信息
 */
void showHelp() {
    std::cout << "任务管理系统命令:\n"
              << "  add <描述> <优先级(low/medium/high)> <截止日期(YYYY-MM-DD)> - 添加新任务\n"
              << "  delete <任务ID> - 删除任务\n"
              << "  list [priority|date] - 列出所有任务 (可选按优先级或日期排序)\n"
              << "  update <任务ID> [desc <新描述>] [priority <新优先级>] [date <新日期>] - 更新任务\n"
              << "  help - 显示帮助信息\n"
              << "  exit - 退出程序\n";
}

/**
 * @brief 解析用户输入并执行相应命令
 * @param input 用户输入
 * @param manager 任务管理器
 * @return std::string 命令执行结果
 */
std::string parseAndExecuteCommand(const std::string& input, TaskManager& manager) {
    std::istringstream iss(input);
    std::string command;
    iss >> command;
    
    try {
        if (command == "add") {
            std::string description, priorityStr, dueDate;
            
            // 跳过空格并检查引号
            iss >> std::ws;
            if (iss.peek() != '"') {
                return "错误: 描述需要用引号括起来";
            }
            iss.get(); // 跳过开头的引号
            
            // 读取直到结束引号
            std::getline(iss, description, '"');

            // 读取优先级和截止日期
            iss >> std::ws >> priorityStr >> dueDate;
            
            // 输入验证
            if (description.empty()) {
                return "错误: 描述不能为空";
            }
            if (priorityStr.empty()) {
                return "错误: 缺少优先级";
            }
            if (dueDate.empty()) {
                return "错误: 缺少截止日期";
            }
            
            Priority priority = Task::stringToPriority(priorityStr);
            auto cmd = std::make_unique<AddTaskCommand>(description, priority, dueDate);
            return cmd->execute(manager);
        }
        else if (command == "delete") {
            int id;
            if (!(iss >> id)) {
                return "错误: 需要提供任务ID";
            }
            auto cmd = std::make_unique<DeleteTaskCommand>(id);
            return cmd->execute(manager);
        }
        else if (command == "list") {
            std::string sortBy;
            iss >> sortBy;
            auto cmd = std::make_unique<ListTasksCommand>(sortBy);
            return cmd->execute(manager);
        }
        else if (command == "update") {
            int id;
            if (!(iss >> id)) {
                return "错误: 需要提供任务ID";
            }
            
            std::string token;
            std::string newDesc;
            std::optional<Priority> newPriority;
            std::string newDate;

            while (iss >> token) {
                if (token == "desc") {
                    iss >> std::ws;
                    if (iss.peek() != '"') {
                        return "错误: 描述需要用引号括起来";
                    }
                    iss.get();
                    std::getline(iss, newDesc, '"');
                } else if (token == "priority") {
                    std::string prioStr;
                    iss >> prioStr;
                    newPriority = Task::stringToPriority(prioStr);
                } else if (token == "date") {
                    iss >> newDate;
                }
            }
            
            auto cmd = std::make_unique<UpdateTaskCommand>(id, newDesc, newPriority, newDate);
            return cmd->execute(manager);
        }
        else if (command == "help") {
            showHelp();
            return "";
        }
        else if (command == "exit") {
            return "exit";
        }
        else {
            return "错误: 未知命令 '" + command + "'";
        }
    } catch (const std::exception& e) {
        return "错误: " + std::string(e.what());
    }
}

int main() {

    initSystemEncoding();

    // 初始化数据存储和任务管理器
    auto dataStore = std::make_unique<FileDataStore>("tasks.dat");
    TaskManager manager(std::move(dataStore));
    
    // 显示欢迎信息和帮助
    std::cout << "欢迎使用任务管理系统!\n";
    showHelp();
    std::cout << "请输入命令:\n";
    
    // 主循环
    while (true) {
        std::cout << "> ";
        std::string input;
        std::getline(std::cin, input);
        
        if (input.empty()) {
            continue;
        }

        std::string result = parseAndExecuteCommand(input, manager);
        
        if (result == "exit") {
            std::cout << "保存数据并退出...\n";
            break;
        }
        
        if (!result.empty()) {
            std::cout << result << "\n";
        }
    }
    
    return 0;
}